package com.gw.vip.server.sign;

import com.alibaba.fastjson.JSONObject;
import com.gw.vip.common.enums.StatusEnums;
import com.gw.vip.common.exception.ExceptionEnums;
import com.gw.vip.common.exception.ServiceException;
import com.gw.vip.server.constants.VipServerKey;
import com.gw.vip.server.po.ShopInfo;
import com.gw.vip.server.service.dao_service.ShopInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 签名切面
 *
 * @author GW
 */
@Slf4j
@Aspect
@Component
@Order(2)
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SignAspect {

    private final SignService signService;
    private final ShopInfoService shopInfoService;

    @Pointcut("@annotation(com.gw.vip.server.sign.RequiredSign)")
    public void sign() {

    }

    @Around("sign()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        if (args.length == 0) {
            throw new ServiceException("无效参数");
        }
        Object params = args[0];
        JSONObject paramsJson = (JSONObject) JSONObject.toJSON(params);

        String shopId = paramsJson.getString(VipServerKey.SHOP_ID);
        if (StringUtils.isBlank(shopId)){
            log.error("没有店铺号参数");
            throw new ServiceException(ExceptionEnums.ERROR_PARAMS, "没有店铺号参数！");
        }
        ShopInfo shopInfo = shopInfoService.getById(shopId);
        if (shopInfo==null){
            log.error("店铺信息不存在！");
            throw new ServiceException(ExceptionEnums.ERROR_PARAMS, "无效店铺！");
        }
        if(!shopInfo.getStatus().equals(StatusEnums.SUCCESS.getCode())){
            log.error("店铺状态无效。状态【{}】", shopInfo.getStatus());
            throw new ServiceException(ExceptionEnums.BUSINESS_FORBIDDEN, "店铺状态无效！");
        }
        String key = shopInfo.getAccessKey();
        signService.checkSign(paramsJson, key);

        Object proceed;
        // 执行方法
        proceed = pjp.proceed();
        return proceed;
    }
}
